package cn.wlbw.service;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.wlbw.dao.NDao;
import cn.wlbw.model.Loot;
import org.nutz.dao.Chain;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;

import java.util.ArrayList;
import java.util.List;

public class DataService {

    private Dao dao = NDao.dao;

    public static void main(String[] args) {
        DataService service = new DataService();

    }

    void addRaidsTime(String teamNo,String date){
        dao.insert("time",Chain.make("teamNo",teamNo).add("date",date));
    }

    JSONArray raid_time() {
        return sql2Array("SELECT\n" +
                "\tt.date AS '开团日期',\n" +
                "\tt.teamNo as '团队',\n" +
                "\tsum( l.points ) AS '消耗总分',\n" +
                "\tmin( l.date ) AS '1号BOSS通过时间',\n" +
                "\tmax( l.date ) AS '副本通过时间',\n" +
                "\tROUND( ( UNIX_TIMESTAMP( max( l.date ) ) - UNIX_TIMESTAMP( min( l.date ) ) ) / 60 ) AS '消耗时间（分钟）' \n" +
                "FROM\n" +
                "\ttime t\n" +
                "\tLEFT JOIN loot l ON t.date = LEFT ( date_sub( l.date, INTERVAL 12 HOUR ), 10 ) \n" +
                "GROUP BY\n" +
                "\tt.date");
    }


    void initLoots() {
        dao.clear(Loot.class);
        dao.insert(getLoots());
    }


    private JSONArray sql2Array(String sqlStr) {
        Sql sql = Sqls.create(sqlStr);
        sql.setCallback(Sqls.callback.records());
        dao.execute(sql);
        return new JSONArray(sql.getList(Record.class));
    }

    private List<Loot> getLoots() {
        List<Loot> list = new ArrayList<>();
        int page = 1;
        while (true) {
            String s = HttpUtil.get("http://webdkp.wowcat.net/dkp/%E6%9B%BC%E5%A4%9A%E5%9F%BA%E5%B0%94/%E4%BA%94%E7%81%B5%E9%9C%B8%E6%AD%A6/Loot/" + page + "/date/desc");
            if (s.contains("未查到拾取记录")) {
                return list;
            }
            page++;
            String[] split = s.split("\n");
            for (String s1 : split) {
                if (s1.contains("{") && s1.contains("}")) {
                    Loot loot = new Loot();
                    int begin = s1.indexOf("{");
                    int end = s1.lastIndexOf("}");
                    String line = s1.substring(begin, end + 1);
                    line = UnicodeUtil.toString(line);
                    JSONObject object = JSONUtil.parseObj(line);
                    loot.setName(object.getStr("name"));
                    loot.setPoints(object.getInt("points"));
                    loot.setPlayer(object.getStr("player"));
                    loot.setDate(object.getStr("datestring"));
                    list.add(loot);
                }
            }
        }
    }
}
